import jwt from "jsonwebtoken";
import { Context } from "nb2";
import { Token } from "./model.js";

/**
 * 获取token
 * @param ctx
 */
export function getToken(ctx: Context) {
  return new Promise<{ uid: number } | undefined>((resolve) => {
    const token = ctx.req.headers["authorization"];
    if (!token) {
      return resolve(undefined);
    }

    try {
      const info = jwt.verify(token, process.env.JWT_KEY!) as Token;
      resolve(info);
    } catch (err) {
      resolve(undefined);
    }
  });
}

/**
 * 生成随机数字
 * 不包含0
 */
export function generateRandom(n: number) {
  let temp = Math.random()
    .toString()
    .substring(2, n + 2);

  if (temp.includes("0")) {
    return generateRandom(n);
  }
  return temp;
}
